#include "StdAfx.h"
#include "Nod.h"
#include <math.h>


Nod::Nod(CPoint centerPoint, int r)
    :Figure(CRect(centerPoint.x - r,centerPoint.y - r, centerPoint.x + r, centerPoint.y + r))
{
	this->radius = r;
	this->name = 0;
}

Nod::Nod(const CRect& rect)
    :Figure(rect)
{
   this->name = 0;
}

Nod::~Nod(void)
{
}

int Nod::Name()
{
	return name;
}

void Nod::Name(const int name)
{
	this->name = name;
}

void Nod::Draw( CDC* pDC )
{

	pDC->Ellipse(&enclosingRect);
}

bool Nod::HasPoint(const CPoint& point)
{
	return GetRadiusFromCentre(point) <= radius;
}

bool Nod::IntersectWith( const CRect& rect )
{
    CPoint c1 = rect.CenterPoint();
    CPoint c2 = enclosingRect.CenterPoint();

    float distance = sqrt(static_cast<double>(abs((c2.x-c1.x)*(c2.x - c1.x)+(c2.y - c1.y)*(c2.y - c1.y))));
    TRACE("Distance %2f r1 = %2i r2 = %2i\r\n",distance,enclosingRect.Width() >> 1,rect.Width() >> 1);


    return distance <= ((enclosingRect.Width() >> 1) + (rect.Width() >> 1));
}

bool Nod::HasPointOnBorder(const CPoint& point)
{
	float newRadius = GetRadiusFromCentre(point);

	return abs(radius - newRadius) < 2;
}

void Nod::UpdateSize(const CPoint& point, const CRect& rect)
{
	float newRadius = GetRadiusFromCentre(point);

    CRect newRect(enclosingRect);
    newRect.InflateRect(newRadius - radius,newRadius - radius);
    newRect.NormalizeRect();
    if (newRect.left > rect.left && newRect.right < rect.right && newRect.top > rect.top && newRect.bottom < rect.bottom)
    {
        radius = newRadius;
        enclosingRect = newRect;
        TRACE("New radius %2f  %2i\r\n",radius,enclosingRect.Width());
    }

}

inline float Nod::GetRadiusFromCentre( const CPoint& point )
{
    int y = abs(point.y - (enclosingRect.top + radius));
    int x = abs(point.x - (enclosingRect.left + radius));
    
    return sqrt(static_cast<long double>(x*x + y*y));
}
